<template>
  <!--  TODO 部门权限 -->
  <div class="page-container">
    <el-col :span="10" :offset="14">
      <el-button type="primary" icon="ele-CirclePlusFilled" size="small" @click="invite">邀请加入</el-button>
      <el-button type="danger" icon="ele-DeleteFilled" size="small" @click="dissolution">解散管理组</el-button>
      <el-button @click="batchMoveMember" size="small" icon="ele-Rank" type="info">批量移动</el-button>
      <el-button size="small">申请人列表</el-button>
    </el-col>
    <el-table :data="treeData" row-key="id" default-expand-all size="small" class="tableList" table-layout="fixed"
              border>
      <el-table-column label="部门组名称" align="left" prop="name" width="180px">
        <!--  <template v-slot="{ row, column, $index }">
           <div style="display: flex;justify-content: flex-start;">
             <span :style="{ marginLeft: row.level * 10 + 'px' }">{{ row.label }}</span>
             <el-button link type="primary" icon="ele-Edit" size="small" @click="editDepartment(row)" />
           </div>
         </template> -->
      </el-table-column>
      <el-table-column label="部门组权限" align="center" width="180px">
        <template v-slot="{ row }">
          <div>
            <span v-for="sm in  row.sysMenus"> {{ sm.title }}、</span>
            <el-button link type="primary" icon="ele-Edit" size="small" @click="editAuthority(row.id)"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150px">
        <template v-slot="{ row }">
          <div class="table-btn">
            <el-button type="primary" link icon="ele-CirclePlusFilled" size="small" @click="addMember(row)"
                       class="bgBtn">添加成员
            </el-button>
          </div>
          <div class="table-btn">
            <el-button type="warning" link icon="ele-Plus" size="small" @click="createGroup(row)"
                       class="bgBtn">新增下级管理组
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="成员姓名" align="left" width="200px">
        <template v-slot="{ row }">
          <div style="flex:1;display:flex;flex-direction: column;">
            <div v-for="(user, index) in row.sysUsers" :key="user.id" style="flex: 1;height:100%">
              <el-row class="order-row-item" style="height:100%">
                <el-col>{{ user.nickname }}
                  <el-button link type="danger" size="small" @click="removeMember(user,row.id)">移除</el-button>
                  <el-button link type="primary" size="small" @click="moveMember(user,row.id)">移动</el-button>
                </el-col>
              </el-row>

                          <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                        v-if="index < row.sysUsers.length - 1"/>
            </div>
            <div v-for="(deptStaffs, index) in row.sysDeptStaffs" :key="deptStaffs.id" style="flex: 1;height:100%">
              <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                          v-if="index == 0"/>
              <el-row class="order-row-item" style="height:100%">
                <el-col>
                  {{ deptStaffs.name }}
                </el-col>
              </el-row>
                          <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                        v-if="index < row.sysDeptStaffs.length - 1"/>
            </div>

          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="120px">
        <template v-slot="{ row }">
          <div style="flex:1;display:flex;flex-direction: column;">
            <div v-for="(user, index) in row.sysUsers" :key="user.id" style="flex: 1;height:100%">
              <el-row class="order-row-item" style="height:100%">
                <el-col>
                  <div>
                    <el-tag size="small" type="primary">已加入
                    </el-tag>
                  </div>
                </el-col>
              </el-row>
              <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                          v-if="index < row.sysUsers.length - 1"/>
            </div>

            <div v-for="(deptStaffs, index) in row.sysDeptStaffs" :key="deptStaffs.id" style="flex: 1;height:100%">
              <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                          v-if="index == 0"/>
              <el-row class="order-row-item" style="height:100%">
                <el-col>
                  <div>
                    <el-tag size="small" type="danger">未加入
                    </el-tag>
                    <el-button size="small" link @click="remind(deptStaffs)"
                               style="color:#409eff;">提醒
                    </el-button>
                  </div>
                </el-col>
              </el-row>

              <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                          v-if="index < row.sysDeptStaffs.length - 1"/>
            </div>



          </div>
        </template>
      </el-table-column>
      <el-table-column label="成员身份" align="center" width="120px">
        <template v-slot="{ row }">
          <div style="flex:1;display:flex;flex-direction: column;">
            <div v-for="(user, index) in row.sysUsers" :key="user.id" style="flex: 1;height:100%">
              <el-row class="order-row-item" style="height:100%">
                <el-col>
                  <div>
                    {{ user.deptType === '0' ? '普通成员' : '管理员' }}
                    <el-button link type="primary" icon="ele-Edit" size="small" @click="editIdentity(user,row.id)"/>
                  </div>
                </el-col>
              </el-row>
              <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                          v-if="index < row.sysUsers.length - 1"/>
            </div>

            <div v-for="(deptStaffs, index) in row.sysDeptStaffs" :key="deptStaffs.id" style="flex: 1;height:100%">
              <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                          v-if="index == 0"/>
              <el-row class="order-row-item" style="height:100%">
                <el-col>
                  <div>
                    {{ deptStaffs.type == '0' ? '普通成员' : '管理员' }}
                    <el-button link type="primary" icon="ele-Edit" size="small" @click="editIdentity(deptStaffs,row.id)"/>
                  </div>
                </el-col>
              </el-row>
              <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                          v-if="index < row.sysDeptStaffs.length - 1"/>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="所属部门" align="center" width="120px">
        <template v-slot="{ row }">
          <!-- <div style="flex:1;display:flex;flex-direction: column;">
            <div v-for="(order, index) in row.member" :key="order.id" style="flex: 1;height:100%">
              <el-row class="order-row-item" style="height:100%">
                <el-col>{{ order.department }}</el-col>
              </el-row>
              <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                v-if="index < row.member.length - 1" />
            </div>
          </div> -->
        </template>
      </el-table-column>
      <el-table-column label="岗位" width="120px" align="center">
        <template v-slot="{ row }">
          <!-- <div style="flex:1;display:flex;flex-direction: column;">
            <div v-for="(order, index) in row.member" :key="order.id" style="flex: 1;height:100%">
              <el-row class="order-row-item" style="height:100%">
                <el-col>{{ order.post }}</el-col>
              </el-row>
              <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                v-if="index < row.member.length - 1" />
            </div>
          </div> -->
        </template>
      </el-table-column>
      <el-table-column label="手机号" width="120px" align="center">
        <template v-slot="{ row }">
          <div style="flex:1;display:flex;flex-direction: column;">
            <div v-for="(user, index) in row.sysUsers" :key="user.id" style="flex: 1;height:100%">
              <el-row class="order-row-item" style="height:100%">
                <el-col>{{ user.phone }}</el-col>
              </el-row>
              <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                          v-if="index < row.sysUsers.length - 1"/>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="操作" align="center" width="150px">
        <template v-slot="{ row }">
          <div style="flex:1;display:flex;flex-direction: column;">
            <div v-for="(order, index) in row.sysUsers" :key="order.id" style="flex: 1;height:100%">
              <el-row class="order-row-item" style="height:100%">
                <el-col>
                  <div>

                  </div>
                </el-col>
              </el-row>
              <el-divider style="margin: 0 -8px;width:calc(100% + 16px);border-color:var(--el-border-color-light)"
                v-if="index < row.sysUsers.length - 1" />
            </div>
          </div>
        </template>
      </el-table-column> -->
    </el-table>

    <el-dialog v-model="editAuthorityVisible" title="部门组权限管理" width="340px" :close-on-click-modal="false">
      <el-tree :data="menuData" default-expand-all show-checkbox node-key="id" ref="roleTree" :props="defaultProps">
      </el-tree>
      <template #footer>
        <el-button size="small" type="primary" @click="saveDeptRole">保 存</el-button>
      </template>
    </el-dialog>

    <create-member-and-group v-model:dialogDrawer="createMemberAndGroupVisible" :optTitle="optTitle" :type="type"
                             :treeData="treeData"
                             :addTreeData = "addTreeData"
                             @onSubmit="getList"/>
    <invite-member v-model:dialogDrawer="inviteMemberVisible" :treeData="treeData" @onSubmit="getList"/>


    <el-dialog v-model="editDeptYypeVisible" title="更改成员身份" width="340px" :close-on-click-modal="false">
      <el-form :model="userDeptForm" :rules="userDeptRules" ref="userDeptRuleForm" label-width="100px" size="small"
               class="demo-ruleForm">
        <el-form-item label="成员身份" prop="type">
          <el-select v-model="userDeptForm.type" placeholder="请选择成员身份">
            <el-option label="管理员" value="1"></el-option>
            <el-option label="普通人员" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" type="primary" @click="submitUserDept(userDeptRuleForm)">保 存</el-button>
      </template>
    </el-dialog>


    <el-dialog v-model="moveUserDeptVisible" title="移动至管理组" width="340px" :close-on-click-modal="false">
      <el-form :model="userDeptForm" :rules="userDeptRules" ref="userDeptRuleForm" label-width="100px" size="small"
               class="demo-ruleForm">
        <el-form-item label="管理组" prop="groupId">
          <el-cascader style="width: 300px" v-model="userDeptForm.groupId" :options="treeData" placeholder="请选择管理组"
                       :props="cascaderProps">
          </el-cascader>
        </el-form-item>
        <el-form-item label="成员身份" prop="type">
          <el-select v-model="userDeptForm.type" placeholder="请选择成员身份">
            <el-option label="管理员" value="1"></el-option>
            <el-option label="普通人员" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" type="primary" @click="submitMoveUserDept(userDeptRuleForm)">保 存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {reactive, toRefs, ref, onMounted, watch} from 'vue'
import {ElMessage, ElMessageBox} from "element-plus";
import CreateMemberAndGroup from '/@/components/organize/CreateMemberAndGroup.vue'
import InviteMember from '/@/components/organize/InviteMember.vue'
import {structureDepartmentData} from '/@/utils/common'
import {updateUserDeptType, getDeptTree, deleteUserDept, moveUserDept, updateDeptRoles} from "/@/api/sys/dept"
import {useMenuApi} from '/@/api/menu'

export default {
  name: "DepartmentAuthority",
  props: {
    treeData: {
      type: Array,
      default: null,
    }
  },
  components: {
    InviteMember,
    CreateMemberAndGroup
  },
  setup(props, context) {
    const {treeData} = toRefs(props)
    const userDeptRuleForm = ref()
    const menuApi = useMenuApi()
    const roleTree = ref()
    //这里的treeData从服务器拿可以省略掉组件传递
    watch(treeData, (newVal) => {
      //监听获取到了新的treeData
      //需要递归重构树结构,才能在table中显示
      console.log("新的treeData数据", newVal)
      structureDepartmentData(newVal, 0) //此处返回数据结构应该和state.list一致
    })
    const state = reactive({
      editAuthorityVisible: false,
      inviteMemberVisible: false,
      createMemberAndGroupVisible: false,
      authorityList: [],
      checkAll: false,
      isIndeterminate: true,
      type: '0',
      moduleList: [
        {
          label: '客户',
          value: '客户'
        },
        {
          label: '订单',
          value: '订单'
        },
        {
          label: '项目',
          value: '项目'
        },
        {
          label: '员工',
          value: '员工'
        },
        {
          label: '候选人',
          value: '候选人'
        },
        {
          label: '市场',
          value: '市场'
        },
        {
          label: '事项',
          value: '事项'
        },
        {
          label: '人事',
          value: '人事'
        },
        {
          label: '品',
          value: '品'
        },
        {
          label: '钱',
          value: '钱'
        },
        {
          label: '供应商',
          value: '供应商'
        },
      ],
      list: [],
      optTitle: [],
      // 编辑身份
      editDeptYypeVisible: false,
      userDeptForm: {
        userId: null,
        deptId: null,
        userName: null,
        type: "0"
      },
      userDeptRules: {
        type: [
          {required: true, message: '请选择成员身份', trigger: 'change'}
        ],
        groupId: [
          {required: true, message: '请选择管理组', trigger: 'change'}
        ]
      },
      // 移动成员到其他部门
      moveUserDeptVisible: false,
      cascaderProps: {
        value: "id",
        label: "name",
        children: "children",
        checkStrictly: true
      },
      menuData: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      userDeptForm2: {
        id: null,
        menuIds:[]
      },
      addTreeData: null
  })

    //添加成员
    const addMember = (data) => {
      state.type = '0'
      state.optTitle = "添加成员"
      state.addTreeData = data
      state.createMemberAndGroupVisible = true
    }
    //移除成员
    const removeMember = (row, deptId) => {
      ElMessageBox.confirm('确定移除成员： ' + row.nickname + ' ？', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        buttonSize: 'small',
        type: 'warning'
      }).then(() => {
        deleteUserDept({userId: row.id, deptId: deptId}).then(res => {
          if (res.code == 0) {
            ElMessage.success('删除成功！')
            getDeptTreeData()
          }
        })

      }).catch((e) => {
        console.log(e)
      })
    }
    //修改部门名称
    const editDepartment = (row) => {
      ElMessageBox.prompt('请输入新的部门名称', '修改部门名称', {
        confirmButtonText: '提交',
        cancelButtonText: '取消',
        inputPlaceholder: row.label
      }).then(({value}) => {
        //修改...
      }).catch(() => {
        //点击了取消
      })
    }
    //修改权限
    const editAuthority = (deptId) => {
      menuApi.getMenuTrees({nowSelectDeptId: ''}).then(res => {
        state.menuData = res.data.menus
      })
      state.userDeptForm2.id = deptId
      state.editAuthorityVisible = true
    }
    //新增下级组
    const createGroup = (data) => {
      state.type = '1'
      state.optTitle = "新增下级组"
      state.addTreeData = data
      state.createMemberAndGroupVisible = true
    }
    //处理全选事件
    const handleCheckAllChange = (val) => {
      if (val) {
        state.authorityList = []
        state.moduleList.forEach(item => {
          state.authorityList.push(item.label)
        })
      } else {
        state.authorityList = []
      }
      state.isIndeterminate = false
    }
    //修改权限回调
    const handleCheckedCitiesChange = (array) => {
      const checkedCount = array.length
      state.checkAll = checkedCount === state.moduleList.length
      state.isIndeterminate = checkedCount > 0 && checkedCount < state.moduleList.length
      //ElMessage.success("修改成功")
    }
    //获取数据
    const getList = () => {

    }
    //提醒
    const remind = (row) => {

    }
    //修改身份
    const editIdentity = (data, deptId) => {
      state.userDeptForm = {
        userId: data.id,
        deptId: deptId,
        userName: data.nickname,
        type: data.deptType
      }
      state.editDeptYypeVisible = true
    }
    //移动成员
    const moveMember = (data, deptId) => {
      state.userDeptForm = {
        userId: data.id,
        deptId: null,
        userName: data.nickname,
        oldDeptId: deptId,
        type: data.deptType,
        groupId: []
      }
      state.moveUserDeptVisible = true
    }
    //批量移动成员
    const batchMoveMember = () => {

    }
    //邀请成员
    const invite = () => {
      state.inviteMemberVisible = true
    }
    //解散组
    const dissolution = () => {
      ElMessageBox.confirm('确定解散组：  ？', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        buttonSize: 'small',
        type: 'warning'
      }).then(() => {
        ElMessage.success('删除成功！')
      }).catch((e) => {
        console.log(e)
      })
    }

    const submitUserDept = (formName) => {
      formName.validate((valid) => {
        if (valid) {
          updateUserDeptType(state.userDeptForm).then(res => {
            if (res.code == 0) {
              ElMessage.success('更改成功！')
              state.editDeptYypeVisible = false
              getDeptTreeData()
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }


    const submitMoveUserDept = (formName) => {
      formName.validate((valid) => {
        if (valid) {
          state.userDeptForm.deptId = state.userDeptForm.groupId != null ? state.userDeptForm.groupId[state.userDeptForm.groupId.length - 1] : "0"
          moveUserDept(state.userDeptForm).then(res => {
            if (res.code == 0) {
              ElMessage.success('更改成功！')
              state.moveUserDeptVisible = false
              getDeptTreeData()
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }

    const saveDeptRole = () => {
      let roles = []
      // 获取实际选中的
      let array = roleTree.value.getCheckedNodes()
      for (let r of array) {
        roles.push(r.id)
      }
      // 获取半包选择，例如父级
      let array2 = roleTree.value.getHalfCheckedNodes()
      for (let r of array2) {
        roles.push(r.id)
      }
      if (roles.length < 1) {
        ElMessage.error('请选择权限！')
      } else {
        state.userDeptForm2.menuIds = roles
        updateDeptRoles(state.userDeptForm2).then(res => {
          if (res.code == 0) {
            ElMessage.success('更改成功！')
            state.editAuthorityVisible = false
            getDeptTreeData()
          }
        })

      }
    }

    const getDeptTreeData = () => {
      getDeptTree("0").then(res => {
        treeData.value = res.data
      })
    }

    onMounted(() => {

    })
    return {
      ...toRefs(state),
      treeData,
      CreateMemberAndGroup,
      InviteMember,
      addMember,
      removeMember,
      editDepartment,
      editAuthority,
      createGroup,
      handleCheckAllChange,
      handleCheckedCitiesChange,
      getList,
      remind,
      editIdentity,
      moveMember,
      batchMoveMember,
      invite,
      dissolution,
      userDeptRuleForm,
      submitUserDept,
      submitMoveUserDept,
      roleTree,
      saveDeptRole
    }
  }
}
</script>

<style scoped lang="scss">
.page-container {

  .tableList {

    margin-top: 20px;

    .order-row-item {
      width: 100%;

      :deep(.el-col) {
        border-right: 1px solid var(--el-border-color-light);
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;

        &:last-child {
          border-right: none;
        }

        &:first-child,
        &:nth-child(2) {
          text-align: left;
          //justify-content: flex-start;
          padding-left: 8px;
        }
      }
    }

    .table-btn {
      display: flex;
      justify-content: space-around;
    }

    .bgBtn:hover {
      border: 1px solid #777777;
    }

    .bgBtn {
      padding: 5px 5px;
    }

  }

}
</style>

<style lang="scss">
.member .cell {
  padding: 0;
}

.el-table__body .member .cell {
  min-height: 70px;
  display: flex;
  align-items: stretch;
  padding: 0;
  text-align: center;
}

.el-table [class*=el-table__row--level] .el-table__expand-icon {
  display: none;
}

//:deep(.el-table__body tbody > .el-table__row:hover){
//  background-color: #f5f7fa !important;
//}
</style>
